#include <gtest/gtest.h>
#include <mutex>
#include <atomic>
#include <logger/logger.h>
#include "utils/thread/thread_pool.h"
#include "utils/thread/runnable.h"
#include "utils/thread/thread.h"

std::mutex gmutex;

std::atomic_int run_count = 0;

void Print(uint64_t id, int num, const std::string &state)
{
    gmutex.lock();
    std::cout << "thread id: " << id << " ,num: " << num << " " << state << std::endl;
    gmutex.unlock();
}

class MyRunnable: public base::Runnable
{

public:
    explicit MyRunnable(int num)
        : num(num)
    {
        run_count.fetch_add(1);
        setRunnableName(std::to_string(99));
    }
    ~MyRunnable() override
    {
        run_count.fetch_sub(1);
    }
private:
    void run() override
    {
        Print(base::Thread::currentThreadId(), num, "start");
        base::Thread::sleep(20);
        Print(base::Thread::currentThreadId(), num, "end");
    }
private:
    int num;
};

TEST(test_utils_thread, test_utils_thread_pool)
{
    base::ThreadPool threadPool;
    threadPool.setMaxThreadCount(2);

    sleep(5);
    threadPool.start(new MyRunnable(1));

    while (run_count > 0)
    {

    }
    EASE_INFO("done");
}

class MyThread: public base::Thread
{
protected:
    void run() override
    {
        while (true)
        {
            EASE_INFO("interpret my thread");
            sleep(3);
            EASE_INFO("interpret my thread done");
        }
        run_count--;
    }
};
TEST(test_utils_thread, test_utils_thread)
{
    MyThread myThread;
    myThread.setThreadName("this is thread");
    myThread.start();
    run_count++;

    while (run_count > 0)
    {

    }
    EASE_INFO("done");
}
